import router from './index'
import useStore from '@/store';

const buildRoute = async () => {
  try {
    const { user } = useStore();
    await user.getTopMenuList()
    // step 0.1
    const { routes } = await user.getUserPermission();
    
    if (!routes || !Array.isArray(routes)) {
      console.warn('No routes returned from getUserPermission');
      return false;
    }
    
    // if (!dataPermissions || !dataPermissions.length) {
    //   // 无数据权限
    //   localStorage.clear();
    //   router.push({ path: '/403', replace: true });
    //   return false;
    // }
  // 路由添加
  const addRoute = function (current: any[], parentName: string) {
    if (!current || !Array.isArray(current)) {
      return;
    }
    current.forEach((item: any) => {
      if (!item) return;
      const { children, ...route } = item;
      // 外链path过滤
      if (route.path && route.path.startsWith('http')) {
        return;
      }
      // 确保route有name属性
      if (!route.name) {
        console.warn('Route missing name property:', route);
        return;
      }
      // step 0.4
      router.addRoute(parentName, route);
      if (children && Array.isArray(children)) {
        addRoute(children, route.name);
      } 
      // else if (parentName == '/') {
      //   debugger
      //   // TODO 逻辑重复添加路由
      //   router.addRoute('Page', route);
      // }
    });
  };

    // step 0.2
    user.setMenu(routes || []);
    // step 0.3
    addRoute(routes, 'Page')
    // 404页面最后添加 
    router.addRoute({ path: '/:catchAll(.*)', redirect: '/404' });
    return true
  } catch (error) {
    console.error('Error building routes:', error);
    return false;
  }
}

export default buildRoute; 